How to Use string_agg()

MS-SQL Server provides a function called string_agg, (in fact there are two functions with the same meaning, one is an aggregate function and the other is a window function). Here we cover the aggregated function. The idea is to concat several strings, from different rows separated by a specified separator.

create table teams (team_name varchar(20), team_member varchar(20));
insert into teams values ('Barcelona','Messi'), ('Barcelona','Piquet'), ('Barcelona','Xavi');
insert into teams values ('Real Madrid','Ronaldo'), ('Real Madrid','Benzema'), ('Real Madrid','Ramos');

This is our base table:

select * from teams;
team_name team_member
Real Madrid Ronaldo
Real Madrid Benzema
Real Madrid Ramos
Barcelona Messi
Barcelona Piquet
Barcelona Xavi

This function concatenates the values of a given column using a separator, because LISTAGG is an aggregate function, the group by clause plays an important role to define what rows are grouped.

select team_name, string_agg(team_member,', ') AS members
from   teams 
group by team_name;
team_name members
Real Madrid Ronaldo, Benzema, Ramos
Barcelona Messi, Piquet, Xavi

The group by team_name clause creates groups of rows with the same value in team_name, then all the members of the same team are concatenated in the same string.

IN THIS PAGE